﻿using AutoMapper;
using ManagementApi.Authorizers;
using ManagementApi.Models;
using ManagementApi.Models.Manage.ProjectGroupMember;
using ManagementApi.Mvc;
using ManagementApi.Mvc.ApplicationContexts;
using ManagementApi.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Modules.Corp;
using Modules.Device;
using Modules.Person;
using Modules.Project;
using NPOI.SS.UserModel;
using NPOI.SS.Util;
using NPOI.XSSF.UserModel;
using PmSoft.Exceptions;

namespace ManagementApi.Controllers.CommanderPannel
{
    /// <summary>
    /// 花名册管理接口
    /// </summary>
    [Route("/api/v1/commander/useemployee")]
    [ApiController]
    [Authorize(Roles = "Commander")]
    public class UseEmployeeController : ControllerBase
    {
        private readonly ProjectGroupMemberService projectGroupMemberService;
        private readonly ProjectService projectService;
        private readonly ProjectGroupService projectGroupService;
        private readonly CorpService corpService;
        private readonly PersonService personService;
        private readonly PersonCorpContractService personCorpContractService;
        private readonly PublicPersonService publicPersonService;
        private readonly ProjectCommanderApplicationContext applicationContext;
        private readonly CheckinDeviceService projectCheckinDeviceService;
        private readonly CheckinDeviceCommandService projectCheckinDeviceCommandService;
        private readonly PersonBankService personBankService;
        private readonly IMapper mapper;
        private readonly ExportService exportService;
        private readonly ProjectOwnAuthorizer ownAuthorizer;

        public UseEmployeeController(
            ProjectGroupMemberService projectGroupMemberService,
            ProjectService projectService,
            ProjectGroupService projectGroupService,
            CorpService corpService,
            PersonService personService,
            PersonCorpContractService personCorpContractService,
            PublicPersonService publicPersonService,
            ProjectCommanderApplicationContext applicationContext,
            CheckinDeviceService projectCheckinDeviceService,
            CheckinDeviceCommandService projectCheckinDeviceCommandService,
            PersonBankService personBankService,
            IMapper mapper,
                 ExportService exportService,
                 ProjectOwnAuthorizer ownAuthorizer
            )
        {
            this.projectGroupMemberService = projectGroupMemberService;
            this.projectService = projectService;
            this.projectGroupService = projectGroupService;
            this.corpService = corpService;
            this.personService = personService;
            this.personCorpContractService = personCorpContractService;
            this.publicPersonService = publicPersonService;
            this.applicationContext = applicationContext;
            this.projectCheckinDeviceService = projectCheckinDeviceService;
            this.projectCheckinDeviceCommandService = projectCheckinDeviceCommandService;
            this.mapper = mapper;
            this.exportService = exportService;
            this.ownAuthorizer = ownAuthorizer;
        }

        /// <summary>
        /// 现场管理人员（分页）
        /// </summary>
        /// <param name="query"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        [HttpGet("page_managerEmployees")]
        public ApiResult<PageDto<UseEmployeeDto>> GetUseManagerEmployees([FromQuery] ProjectGroupMemberQuery query, int pageIndex = 1, int pageSize = 20)
        {
            query.ProjectId = applicationContext.CurrentProjectInfo.ProjectId;
            query.IsManager = true;
            var data = projectGroupMemberService.GetProjectGroupMembersByManager(query, pageIndex, pageSize);
            var corps = corpService.GetCorpsByCorpIds(data.Select(a => a.CorpId));
            var projects = projectService.GetProjectInfoByProjectIds(data.Select(a => a.ProjectId));
            var persons = personService.GetPersons(data.Select(a => a.PersonId));
            var personCorpContracts = personCorpContractService.GetPersonCorpContractsByProjectIds(data.Select(a => a.ProjectId));
            var dtos = data.AsPageDto(source => { return source.AsManagerEmployeeDto(corps, projects, persons, personCorpContracts); });
            return ApiResult<PageDto<UseEmployeeDto>>.Success(dtos);
        }

        /// <summary>
        /// 用工工人信息（分页）
        /// </summary>
        /// <param name="query"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        [HttpGet("page_useEmployees")]
        public ApiResult<PageDto<UseEmployeeDto>> GetUseEmployees([FromQuery] ProjectGroupMemberQuery query, int pageIndex = 1, int pageSize = 20)
        {
            query.ProjectId = applicationContext.CurrentProjectInfo.ProjectId;
            var data = projectGroupMemberService.GetProjectGroupMembers(query, pageIndex, pageSize);
            var corps = corpService.GetCorpsByCorpIds(data.Select(a => a.CorpId));
            var projects = projectService.GetProjectInfoByProjectIds(data.Select(a => a.ProjectId));
            var groups = projectGroupService.GetProjectGroups(data.Select(a => a.GroupId));
            var persons = personService.GetPersons(data.Select(a => a.PersonId));
            var personCorpContracts = personCorpContractService.GetPersonCorpContractsByProjectIds(data.Select(a => a.ProjectId));
            var dtos = data.AsPageDto(source => { return source.AsUseEmployeeDto(corps, projects, groups, persons, personCorpContracts); });
            return ApiResult<PageDto<UseEmployeeDto>>.Success(dtos);
        }

        /// <summary>
        /// 导出Excel
        /// </summary>
        /// <returns></returns>
        [HttpGet("export")]
        public IActionResult Export([FromQuery] ProjectGroupMemberQuery query, int pageIndex = 1, int pageSize = 9999)
        {
            if (!query.ProjectId.HasValue) query.ProjectId = applicationContext.CurrentProjectInfo.ProjectId;
            var data = projectGroupMemberService.GetProjectGroupMembers(query, pageIndex, pageSize);

            var projectInfo = projectService.GetProjectInfo(query.ProjectId ?? 0) ?? throw new BusinessException("项目不存在");

            List<UseEmployeeExportDto> exportDtos = data.AsUseEmployeeExportDtos().ToList();
            // 创建一个新的Excel工作簿
            IWorkbook workbook = new XSSFWorkbook();

            // 创建一个新的工作表
            ISheet sheet = workbook.CreateSheet("Sheet1");

            #region 表头

            // 合并行和列的方式设置单元格的边界
            CellRangeAddress left = new CellRangeAddress(0, 1, 0, 10);
            CellRangeAddress right = new CellRangeAddress(0, 1, 11, 17);
            sheet.AddMergedRegion(left);
            sheet.AddMergedRegion(right);
            // 创建一个新的行
            IRow row = sheet.CreateRow(0);
            ICell cell = row.CreateCell(0);
            ICell cell2 = row.CreateCell(11);
            // 创建字体对象
            IFont font = workbook.CreateFont();
            font.FontHeightInPoints = 20; // 设置字体大小为 12

            // 设置单元格样式
            ICellStyle cellStyle = workbook.CreateCellStyle();
            cellStyle.Alignment = HorizontalAlignment.Center;//居中
            cellStyle.SetFont(font);
            cell.CellStyle = cellStyle;
            cell2.CellStyle = cellStyle;
            // 设置单元格的值
            cell.SetCellValue(projectInfo.Name);
            cell2.SetCellValue(projectInfo.PrjNum);

            int index = 1;

            #endregion 表头

            index++;
            exportService.CellRange(sheet, workbook, index, 0, 0, "姓名", "性别", "身份证号码", "联系电话", "家庭地址", "籍贯", "发卡银行", "银行卡号", "参建单位", "班组名称", "工种类别", "是否项目管理员", "班组进场时间", "班组离场时间", "是否班组长", "是否签订劳动合同", "人员进场日期", "人员离场日期");

            #region 数据部分

            foreach (var item in exportDtos)
            {
                index++;
                exportService.CellRange(sheet, workbook, index, 0, 0, item.PersonName, item.Gender, item.CardNumber, item.Mobile, item.Address, item.Nation, item.BankName, item.BankCardNo, item.CorpName, item.GroupName, item.TypeName, item.IsManager, item.GroupStartDate, item.GroupEndDate, item.IsLeader, item.IsContract, item.PersonStartDate, item.PersonEndDate);
            }
            // 创建列并设置最小宽度
            int columnWidth = 20;
            int columnIndex = 0;
            /*  sheet.SetColumnWidth(columnIndex, columnWidth * 200);*/ // 设定列宽度，参数为1/256个字符宽度
                                                                        // 自动调整列宽
            for (int i = 0; i < 18; i++)
            {
                // 自动调整列宽
                sheet.AutoSizeColumn(i);
                // sheet.SetColumnWidth(i, Math.Max(columnWidth * 200, sheet.GetColumnWidth(i)));
            }

            #endregion 数据部分

            // 将工作簿保存到内存流中
            using (MemoryStream memoryStream = new MemoryStream())
            {
                workbook.Write(memoryStream);
                // 返回文件内容结果
                return File(memoryStream.ToArray(), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", $"花名册信息表_{DateTime.Now.ToString("yyyyMMddHHmmss ")}.xlsx");
            }
        }
    }
}